/**
 * @file 管理公网资产查询组件间状态
 */
import { createActions, handleActions } from 'redux-actions';
import {
  getZoomeyeOrgConnect,
  getZoomeyeSearchConfig,
  setZoomeyeOrgAccount,
  updateZoomeyeOrg
} from '@api/system';
import lodash from 'lodash';
import { message } from 'antd';

const initState = {
  searchConfigVisible: false, // org配置探测
  tab: 'notVerified', // 列表切换tab
  isUpdating: false, // org数据是否更新中
  initError: false, // 是否进行过org初始化
  activeKey: 'account', // 查询设置tab的key
  accountData: {} // 账户信息
};

export const actions = createActions({
  initOrgManage: () => dispatch => {
    dispatch(actions.checkOrgConfig());
  },
  // 检查org连接是否正常
  checkOrgConnection: () => async () => {
    const result = getZoomeyeOrgConnect();
    return lodash.get(result, 'data.data.status');
  },
  // 检查org查询设置是否初始化数据，是否正在更新
  checkOrgConfig: () => dispatch => {
    getZoomeyeSearchConfig().then(res => {
      const search = lodash.get(res, 'data.data.config.search', {});
      const isUpdating = lodash.get(res, 'data.data.config.isUpdating', false);
      const email = lodash.get(res, 'data.data.config.email', '');
      const apiKey = lodash.get(res, 'data.data.config.apiKey', false);

      //判断org配置中搜索是否全为空
      const initError = Object.values(search).every(i => !i || (Array.isArray(i) && !i.length));

      const activeKey = apiKey ? 'config' : 'account';
      dispatch(
        actions.setState({ initError, isUpdating, activeKey, accountData: { email, apiKey } })
      );
    });
  },
  openModal: () => dispatch => {
    dispatch(actions.setState({ searchConfigVisible: true }));
  },
  closeModal: () => (dispatch, getState) => {
    const state = getState();
    const apiKey = lodash.get(state, 'orgManage.accountData.apiKey', false);
    const activeKey = apiKey ? 'config' : 'account';
    dispatch(actions.setState({ searchConfigVisible: false, activeKey }));
  },
  setIsUpdating: isUpdating => dispatch => {
    dispatch(actions.setState({ isUpdating }));
  },
  handleTabChange: key => (dispatch, getState) => {
    const state = getState();
    const apiKey = lodash.get(state, 'orgManage.accountData.apiKey', false);
    if (apiKey) {
      dispatch(actions.setState({ activeKey: key }));
    }
  },
  /**
   * @description 立即更新org数据
   * @param {boolean} check 是否检查连接
   * */
  updateImmediately: check => async dispatch => {
    if (check) {
      const status = await dispatch(actions.checkOrgConnection());
      if (!status) {
        message.error('无法访问到公共互联网，请检查您的网络权限配置！');
      }
    }
    updateZoomeyeOrg()
      .then(() => {
        message.success('更新成功');
        dispatch(actions.setState({ isUpdating: true }));
      })
      .catch(() => {
        message.error('更新失败');
      });
  },
  // 更新org帐号
  updateZoomeyeOrgAccount: params => dispatch => {
    setZoomeyeOrgAccount(params)
      .then(res => {
        const status = lodash.get(res, 'data.data.status', false);
        if (!status) {
          message.warn('无法连接到zoomeye.org');
          return;
        }
        dispatch(
          actions.setState({
            activeKey: 'config',
            accountData: { email: params.email, apiKey: true }
          })
        );
      })
      .catch(() => {
        message.warn('无法连接到zoomeye.org');
      });
  },
  setState: value => value
});

const reducer = handleActions(
  {
    setState: (state, action) => {
      const { error, payload } = action;
      if (error || typeof payload !== 'object') {
        window.console.error(error);
        return state;
      } else if (typeof payload === 'object') {
        return { ...state, ...payload };
      } else {
        window.console.error('payload must be an object in setState');
        return state;
      }
    }
  },
  initState
);

export default reducer;
